<?php

namespace app\admin\controller\mall;

use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Time;
use app\common\model\MachineMachine;
use app\common\model\MallOrderGoods;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\common\model\MallOrder;
use app\common\model\MallUser;
use think\App;

/**
 * @ControllerAnnotation(title="订单排名")
 */
class OrderRanking extends AdminController
{
    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = (new MallOrder());
        $this->field = "*,openid as wechat,id as get_goods";

    }

    /**
     * @NodeAnotation(title="排名列表")
     * @return array|mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames([],'g');

            if (!empty($this->request->cate_machine)) {
                $machine = (new MachineMachine())
                    ->where('machine_cate', $this->request->cate_machine)
                    ->select()->toArray();
                $where[] = [
                    ['g.machine_id', 'in', array_column($machine, 'machine_id')]
                ];
            }

            $lists = (new MallOrderGoods())
                ->alias('g')
                ->join('mall_order o','g.order_id = o.id')
                ->field('count(g.id) as counts,specs_title,specs_name,specs,g.create_time')
                ->group('specs_name')
                ->where($where)
                ->where([
                    ['o.order_status','<>',0]
                ])
                ->order('counts desc,create_time desc')
                ->paginate($limit)
                ->toArray();
            return Show::json_show(Status::lay_normal, "ok", $lists['data'], $lists['total']);
        }
        $toTime = Time::month();
        return $this->fetch('', [
            'start_time' => date('Y-m-d H:i:s', $toTime[0]),
            'end_time' => date('Y-m-d H:i:s', $toTime[1])
        ]);
    }

    public function add()
    {
    }

    public function edit($id)
    {
    }
}